package com.bamboo.msmservice.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020-07-04
 */
@Slf4j
@Component
public class MsmUtil {


    private static final String REGION_ID = "default";

    @Value("${aliyun.oss.file.keyid}")
    private String keyId;

    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;

    @Value("${aliyun.msm.signName}")
    private String signName;

    @Value("${aliyun.msm.templateCode}")
    private String templateCode;

    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;

    public static String SIGN_NAME;
    public static String TEMPLATE_CODE;

    @PostConstruct
    public void init() {
        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
        SIGN_NAME = signName;
        TEMPLATE_CODE = templateCode;
    }


    private static IAcsClient getIAcsClient() {
        DefaultProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        return new DefaultAcsClient(profile);
    }


    public static boolean send(String phone, String code) {
        IAcsClient client = getIAcsClient();
        // 方便转换JSON
        Map<String, Object> param = new HashMap<>(4);
        param.put("code", code);

        // 设置相关固定的参数
        CommonRequest request = new CommonRequest();
        // request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2020-07-13");
        request.setAction("SendSms");

        // 设置发送相关的参数
        // 手机号
        request.putQueryParameter("PhoneNumbers", phone);
        // 申请阿里云 签名名称
        request.putQueryParameter("SignName", SIGN_NAME);
        // 申请阿里云 模板code
        request.putQueryParameter("TemplateCode", TEMPLATE_CODE);
        // 验证码数据，转换json数据传递
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        try {
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            return response.getHttpResponse().isSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

}
